<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\GiftLessonStudent;
use Illuminate\Support\Facades\DB;

class GiftLessonStudentStatusOnCommand extends Command
{
    protected $signature = 'bills:gift_lesson_student_status_on';

    public function handle()
    {
        $pageSize = 1000;

        $BillingQuery = DB::connection('billing')->table('bills')
            ->where('status', 20)
            ->where('product_id', 6);

        $billTotalNum = $BillingQuery->count();

        for ($page=1; $page<=ceil($billTotalNum/$pageSize); $page++) {
            $bills = $BillingQuery->select('student_id')->skip($pageSize * ($page - 1))->take($pageSize)->get();

            foreach ($bills as $bill) {
                $this->studentStatusOn($bill->student_id);
            }
        }

        $cashBillingQuery = DB::connection('cash_billing')->table('bills')
            ->where('status', 20)
            ->where('recharge_amount', '>=', 3500);
        $cashBillTotalNum = $cashBillingQuery->count();

        for ($page=1; $page<=ceil($cashBillTotalNum/$pageSize); $page++) {
            $cashBills = $cashBillingQuery->select('student_id')->skip($pageSize * ($page - 1))->take($pageSize)->get();

            foreach ($cashBills as $cashBill) {
                $this->studentStatusOn($cashBill->student_id);
            }
        }
    }

    private function studentStatusOn($studentId)
    {
        $student = GiftLessonStudent::find($studentId);
        if (!empty($student)) {
            return;
        }
        $student = new GiftLessonStudent();
        $student->setStudentId($studentId);
        $student->setStatus(GiftLessonStudent::STATUS_UNLOCK);
        $student->save();
        return;
    }

}
